<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="USER_TYPE_NAME" prop="username">
        <el-input
          v-model="queryParams.username"
          :placeholder="`请输入${USER_TYPE_NAME}名称`"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="所属维修店" prop="panId">
        <el-select v-model="queryParams.panId" clearable>
          <el-option
            v-for="item in panList"
            :key="item.id"
            :label="item.username"
            :value="item.panId"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="权限" prop="permissionIds">
        <!-- <el-select
          multiple
          v-model="queryParams.permissionIds"
          clearable
          style="width:300px;"
        >
          <el-option
            v-for="item in authList"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          ></el-option>
        </el-select> -->
        <el-cascader
          v-model="queryParams.permissionIds"
          :options="category"
          :props="props"
          collapse-tags
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button plain size="mini" @click="handleSelectAll">全选</el-button>
        <el-button plain size="mini" @click="handleDelete" type="danger"
          >删除</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(1)"
          >锁定</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(0)"
          >解锁</el-button
        >
        <el-button plain size="mini" @click="handleUpload">批量导入</el-button>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column
        label="邮箱"
        align="center"
        prop="email"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="USER_TYPE_NAME"
        align="center"
        prop="username"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="添加时间	"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="权限"
        align="center"
        :show-overflow-tooltip="true"
        prop="cmsPermissionList"
      >
        <template slot-scope="scope">
          <span>{{ permissionFormat(scope.row.cmsPermissionList) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="账号类型" prop="pan">
          <el-radio-group v-model="form.pan">
            <el-radio :label="1">主账号</el-radio>
            <el-radio :label="0">子账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属账号" prop="panId" v-if="form.pan == 0">
          <el-select
            v-model="form.panId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="权限" prop="cmsPermissionList">
          <el-tree
            :data="category"
            show-checkbox
            default-expand-all
            node-key="categoryId"
            :props="defaultProps"
            ref="tree"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="formLoading" type="primary" @click="submitForm(false)">确 定</el-button>
        <el-button :loading="formLoading" type="danger" @click="submitForm(true)"
          >保存并邮件通知</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入 -->
    <el-dialog
      title="批量导入"
      :visible.sync="openUpload"
      width="600px"
      append-to-body
      @close="cancelUpload"
    >
      <div>
        <el-button type="danger" @click="downLoadTemp"
          >点击下载模板文件</el-button
        >
        <div>
          <div class="upload-title">上传：</div>
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="uploadFileUrl"
            :data="uploadData"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :on-success="handleUploadSuccess"
            :on-change="handleChange"
            :file-list="fileList"
            :auto-upload="false"
            :limit="1"
            :headers="headers"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <!-- <el-button
              style="margin-left: 10px;"
              size="small"
              type="success"
              @click="submitUpload"
              >上传到服务器</el-button
            > -->
            <div slot="tip" class="el-upload__tip">
              只能上传excel文件，且不超过500kb
            </div>
          </el-upload>
        </div>
        <!-- <div>
          <div class="upload-title">账号类型：</div>
          <el-radio-group v-model="uploadData.pan">
            <el-radio :label="1">主账号</el-radio>
            <el-radio :label="0">子账号</el-radio>
          </el-radio-group>
        </div>
        <div v-if="uploadData.pan == 0">
          <div class="upload-title">所属账号：</div>
          <el-select
            v-model="uploadData.panId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div> -->
        <div>
          <div class="upload-title">权限：</div>
          <el-tree
            :data="category"
            show-checkbox
            default-expand-all
            node-key="categoryId"
            :props="defaultProps"
            ref="tree2"
          >
          </el-tree>
          <!-- <el-checkbox-group v-model="uploadData.permissionIds">
            <el-checkbox
              v-for="item in category"
              :key="item.categoryId"
              :label="item.categoryId"
              >{{ item.categoryName }}</el-checkbox
            >
          </el-checkbox-group> -->
        </div>
        <div class="upload-tips">
          注：<br />
          1.下载模板文件，请上传xls格式文件<br />
          2.mb.xls模板文件里第一行（用户名 用户密码 找回密码邮箱）不要删除。<br />
          3.请勿上传相同用户名和邮箱数据<br />
          <!-- 4.不选择权限即默认拥有所有权限<br /> -->
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="formLoading" type="primary" @click="submitUpload(false)">导 入</el-button>
        <el-button :loading="formLoading" type="danger" @click="submitUpload(true)"
          >导入并邮件通知</el-button
        >
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  addType,
  getType,
  delType,
  updateType,
  changeStatus,
  exportUser
} from "@/api/cms/user";
import { getToken } from "@/utils/auth";
import { getPage as getCategoryPage } from "@/api/cms/category";

const USER_TYPE = 1;
const USER_TYPE_NAME = "维修店";

export default {
  name: "Store",
  data() {
    return {
      USER_TYPE_NAME,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: USER_TYPE,
        username: "",
        permissionIds: []
      },
      // 表单参数
      form: {
        pan: 1,
        cmsPermissionList: []
      },
      category: [],
      categoryData: [],
      openUpload: false,
      // 批量导入
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/cms/user/upload",
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {
        permissionIds: [],
        type: USER_TYPE,
        pan: 1,
        panId: ""
      },
      searchLoading: false,
      options: [],
      categoryAuth: [],
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      panList: [],
      authList: [],
      options: [],
      props: {
        children: "children",
        label: "categoryName",
        value: "categoryId",
        multiple: true
      },
      level2Ids: [],
      formLoading: false
    };
  },
  computed: {
    // 表单校验
    rules() {
      return {
        // pan: [{ required: true, message: "请选择账号类型", trigger: "blur" }],
        // panId: [
        //   {
        //     required: this.form.pan == 0,
        //     message: "请选择所属账号",
        //     trigger: "blur"
        //   }
        // ],
        email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          {
            required: this.form.id ? false : true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ]
        // cmsPermissionList: [
        //   { required: true, message: "请选择权限", trigger: "blur" }
        // ]
      };
    }
  },
  created() {
    getCategoryPage().then(response => {
      this.categoryData = [...response.data]; // 列表
      const category = this.handleTree(response.data, "categoryId"); // 树结构
      this.category = [
        // tree
        ...JSON.parse(JSON.stringify(category))
      ];
      this.getList();
    });
  },
  methods: {
    getPanList() {
      listType({ pan: 1, type: USER_TYPE }).then(response => {
        this.panList = response.rows;
      });
    },
    handleCheckChangeImport(obj, checked, child) {
      // console.log(obj, checked, child);
      // if (checked) {
      //   if (obj.parentId != 0) {
      //     // 如果是子节点  判断父节点是否选中  未选择则选中
      //     this.$refs.tree2.setChecked(obj.pid, true);
      //   } else {
      //     const children = this.categoryAuth.find(
      //       x => x.categoryId == obj.categoryId
      //     ).children;
      //     const ids = children.map(x => x.categoryId);
      //     const checkedKeys = this.$refs.tree2.getCheckedKeys();
      //     if (ids.every(x => checkedKeys.indexOf(x) == -1)) {
      //       children.forEach(item => {
      //         this.$refs.tree2.setChecked(item.categoryId, true);
      //       });
      //     }
      //   }
      // } else {
      //   if (obj.parentId == 0) {
      //     this.categoryAuth
      //       .find(x => x.categoryId == obj.categoryId)
      //       .children.forEach(item => {
      //         this.$refs.tree2.setChecked(item.categoryId, false);
      //       });
      //   }
      //   // 如果是父节点取消 则全部子节点取消
      // }
    },
    handleCheckChange(obj, checked, child) {
      // if (checked) {
      //   if (obj.parentId != 0) {
      //     this.$refs.tree.setChecked(obj.pid, true);
      //   } else {
      //     const children = this.categoryAuth.find(
      //       x => x.categoryId == obj.categoryId
      //     ).children;
      //     const ids = children.map(x => x.categoryId);
      //     const checkedKeys = this.$refs.tree.getCheckedKeys();
      //     if (ids.every(x => checkedKeys.indexOf(x) == -1)) {
      //       children.forEach(item => {
      //         this.$refs.tree.setChecked(item.categoryId, true);
      //       });
      //     }
      //   }
      //   // 如果是子节点  判断父节点是否选中  未选择则选中
      // } else {
      //   if (obj.parentId == 0) {
      //     this.categoryAuth
      //       .find(x => x.categoryId == obj.categoryId)
      //       .children.forEach(item => {
      //         this.$refs.tree.setChecked(item.categoryId, false);
      //       });
      //   }
      //   // 如果是父节点取消 则全部子节点取消
      // }
    },
    remoteMethod(query) {
      if (query !== "") {
        this.searchLoading = true;
        listType({ username: query, pan: 1, type: USER_TYPE }).then(
          response => {
            this.options = response.rows;
            this.searchLoading = false;
          }
        );
      } else {
        this.options = [];
      }
    },
    downLoadTemp() {
      window.open(
        `${process.env.VUE_APP_BASE_URL}${process.env.VUE_APP_PUBLIC_PATH}/mb.xls`
      );
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleBeforeUpload() {
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.formLoading = false;
      this.$message.error("导入失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.formLoading = false;
      console.log(res);
      if (res.code == 200) {
        this.$message.success("导入成功");
        this.cancelUpload();
        this.resetForm("queryForm");
        this.handleQuery();
      } else {
        delete file.response;
        file.status = "ready";
        file.percentage = 0;
        this.fileList = [file];
        this.$message.error("导入失败,请检查是否存在重复数据");
      }
    },
    submitUpload(send) {
      const checkedNodes = this.$refs.tree2.getCheckedNodes(false, true);
      if (this.fileList.length == 0) {
        this.$message.error("请选择文件");
        return;
      }
      // if (this.uploadData.pan == 0 && !this.uploadData.panId) {
      //   this.$message.error("请选择所属账号");
      //   return;
      // }

      if (checkedNodes.length == 0) {
        this.$message.error("请选择权限");
        return;
      }

      const cmsPermissionList = checkedNodes.map(x => x.categoryId);
      this.uploadData.permissionIds = cmsPermissionList;
      this.uploadData.send = send;
      console.log("上传");
      this.formLoading = true;
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleUpload() {
      this.openUpload = true;
    },
    cancelUpload() {
      this.$refs.tree2 && this.$refs.tree2.setCheckedKeys([]);
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.uploadData = {
        permissionIds: [],
        pan: 1,
        panId: ""
      };
      this.openUpload = false;
    },
    permissionFormat(cmsPermissionList) {
      let str = [];
      if (this.categoryData && this.categoryData.length > 0) {
        cmsPermissionList.forEach(item => {
          if (item.categoryId < 0) {
            str.push("考试专用");
          } else {
            this.categoryData.forEach(category => {
              if (item.categoryId === category.categoryId) {
                str.push(category.categoryName);
              }
            });
          }
        });
      }
      return str.join(" | ");
    },
    getList() {
      this.loading = true;
      const permissionIds = new Set();

      this.queryParams.permissionIds.forEach(x => {
        x.forEach(y => {
          permissionIds.add(y);
        });
      });

      listType({
        ...this.queryParams,
        permissionIds: Array.from(permissionIds)
      }).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    statusFormat(row, column) {
      return row.status == 0 ? "正常" : "锁定";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        username: undefined,
        password: undefined,
        cmsPermissionList: [],
        pan: 1
      };
      this.$refs.tree && this.$refs.tree.setCheckedKeys([]);
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加" + this.USER_TYPE_NAME;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getType(id).then(response => {
        response.data.password = "";

        // const checkedNodes = response.data.cmsPermissionList.filter(
        //   x => x.categoryId
        // );
        this.form = response.data;
        this.form.cmsPermissionList = this.form.cmsPermissionList.map(
          x => x.categoryId
        );
        this.open = true;
        this.$nextTick(() => {
          setTimeout(() => {
            this.form.cmsPermissionList.forEach(categoryId => {
              this.$refs.tree.setChecked(categoryId, true, false);
            }, 500);
          });
        });

        this.title = "修改" + this.USER_TYPE_NAME;
      });
    },
    /** 提交按钮 */
    submitForm: function(send) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes(false, true);

          if (checkedNodes.length == 0) {
            this.$message.error("请选择权限");
            return;
          }

          const cmsPermissionList = checkedNodes.map(x => ({
            categoryId: x.categoryId
          }));
          this.formLoading = true;
          if (this.form.id != undefined) {
            updateType(
              {
                ...this.form,
                cmsPermissionList,
                type: USER_TYPE
              },
              send
            ).then(response => {
              this.formLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getPanList();
            }).catch(e=>{
              console.log(e);
              this.formLoading = false;
            });
          } else {
            addType(
              { ...this.form, cmsPermissionList, type: USER_TYPE },
              send
            ).then(response => {
              this.formLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getPanList();
            }).catch(e=>{
              console.log(e);
              this.formLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$confirm(
        `是否确认删除编号为[${Ids}]的${this.USER_TYPE_NAME}?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delType(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportUser(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },
    /** 清理缓存按钮操作 */
    handleClearCache() {
      clearCache().then(response => {
        this.msgSuccess("清理成功");
      });
    },
    // 全选
    handleSelectAll() {
      this.$refs.table.toggleAllSelection();
    },
    // 变更状态
    handleChangeStatus(status) {
      changeStatus({
        ids: this.ids,
        status
      }).then(response => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    }
  }
};
</script>
<style scoped lang="scss">
.upload-title {
  font-weight: bold;
  color: #666;
  margin: 10px 0;
}
.upload-tips {
  color: #555;
  margin-top: 40px;
}
</style>
